//
// Created by yangchao on 2022/4/18.
// 2. 两数相加: https://leetcode-cn.com/problems/add-two-numbers/
//

#include "../DataStructure/ListNode.h"
#include <iostream>
using namespace std;

//将两个链表看成是相同长度的进行遍历，如果一个链表较短则在前面补0，比如987+23 = 987+023 = 1010
class AddTwoNumbers {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(-1);
        ListNode* node = dummy;
        int sign = 0;
        while (l1 != nullptr || l2 != nullptr) {
            int v1 = l1 == nullptr? 0 : l1->val;
            int v2 = l2 == nullptr? 0 : l2->val;
            int sum = v1 + v2 + sign;
            sign = sum > 9 ? 1 : 0;
            sum = sum % 10;
            node->next = new ListNode(sum);
            node = node->next;
            if (l1 != nullptr) l1 = l1->next;
            if (l2 != nullptr) l2 = l2->next;
        }
        if (sign == 1) node->next = new ListNode(1);
        return dummy->next;
    }
};



